from datetime import datetime, timedelta
from time import sleep

from pytest_result_sender.send_x import send_mail

data = {
    "passed":0,
    "failed":0,
    "failed_test_name":[],
}

def pytest_runtest_logreport(report: "TestReport") -> None:
    # print(report)
    # print(report.when)
    if report.when == 'call':
        print("本次用例的执行结果是：",report.outcome)
        if report.outcome == 'passed':
            data['passed'] += 1
        elif report.outcome == 'failed':
            data['failed'] += 1
            data['failed_test_name'].append(report.nodeid)


def pytest_collection_finish(session: "Session") -> None:
    # 用例加载完成后，收集全部用例
    print(session.items)
    data['total'] = len(session.items)
    print(f"用例总数： {data['total']} ")

    # 在测试会话结束时打印失败的测试用例名字
    if data['failed'] > 0:
        print("\nFailed tests:")
        for failed_test_name in data['failed_test_names']:
            print(failed_test_name)

def pytest_configure():
    # 配置加载完毕之后执行，所有测试用例之前执行

    data['start_time'] = datetime.now()
    print(f"pytest 开始执行：{data['start_time']}")

def pytest_unconfigure():
    # 配置加载完毕之后执行，所有测试用例之后执行

    data['end_time'] = datetime.now()
    # print(f"{data['end_time']}pytest 结束执行")

    data['duration'] = data['end_time'].replace(microsecond=0) - data['start_time'].replace(microsecond=0)

    # print(f"执行时长：{data['duration'] } ")

    data['pass_ratio'] = data['passed'] / data['total']*100
    data['pass_ratio'] = f"{data['pass_ratio']:.2f}%"

    # print(f"测试通过率：{data['pass_ratio']}")

    content = f"""
    测试执行开始时间：{data['start_time'].strftime('%Y-%m-%d %H:%M:%S')}</br>
    测试用例总数：{data['total']}</br>
    测试执行结束时间：{data['end_time'].strftime('%Y-%m-%d %H:%M:%S')}</br>
    测试执行时长：{data['duration']}</br>
    测试通过条数：{data['passed']}</br>
    测试失败条数：{data['failed']}</br>
    测试失败的用例是：{data['failed_test_name']}</br>
    测试通过率：{data['pass_ratio']}</br>
    """

    print(content)
    send_mail(data['start_time'].strftime('%Y-%m-%d %H:%M:%S'), ["3318550879@qq.com","569118688@qq.com"], subject=' pytest自动化测试结果', content=content)

    # 断言
    # assert timedelta(seconds=5) > data['duration'] >= timedelta(seconds=2)
    # assert data['total'] == 4
    # assert data['passed'] == 3
    # assert data['failed'] == 1
    # assert data['pass_ratio'] == '75.00%'